const router = require('koa-router')()
const sequelize=require('../config/db')
const statusCode=require('../util/status-code')
const {get}=require('../util/ajax')

const Links=sequelize.import('../schema/links')
const Userinfo=sequelize.import('../schema/userinfo')
const IpAddress=sequelize.import('../schema/ipAddress')
IpAddress.sync({force:false})

router.prefix('/api/v1/resume')
router.get('/userinfo/detail/:uuid',async (ctx,next)=>{
  try {
    let uuid=ctx.params.uuid
    const userinfo=await Userinfo.findOne({
      where:{
        uuid
      },
      attributes:{
        exclude:['createdAt', 'updatedAt']
      }
    })
    const links=await Links.findAll({
      where:{
        uuid
      },
      attributes:{
        exclude:['createdAt', 'updatedAt','uuid']
      }
    })
    let data=userinfo.toJSON()
    // console.log(data)
    ctx.body=statusCode.s200({
      ...data,
      links
    })
  }catch (e) {

  }
})

const getUserIp = (req) => {
  return req.headers['x-forwarded-for'] ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress;
}
router.get('/ipAddress',async (ctx,next)=>{
  try {
    let ip=getUserIp(ctx.request)
    let hasIp=await IpAddress.findOne({
      where:{
        ipAddress:ip
      }
    })
    if (hasIp){
      IpAddress.update({
        visitNum:hasIp.visitNum+1
      },{
        where:{
          ipAddress:ip
        }
      })
    } else {
      const {data}=await get(`http://ip.taobao.com/service/getIpInfo.php?ip=${ip}`)
      await IpAddress.create({
        ipAddress:ip,
        address:`${data.country},${data.city}`,
        visitNum: 1
      })

    }
    ctx.body=statusCode.s200(ip)
  }catch (e) {
    ctx.body=statusCode.e401(e)
  }
})

module.exports = router